/* 
 * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU.
 * Copyright (c) 2006-2018 Christian Walter <cwalter@embedded-solutions.at>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

/* ----------------------- System includes ----------------------------------*/
#include "stdlib.h"
#include "string.h"
#include "stdio.h"

#include "../include/mb.h"
#include "../include/mbport.h"
#include "../include/mbframe.h"
#include "mbrtu.h"
#include "mbcrc.h"

/* ----------------------- Defines ------------------------------------------*/
#define MB_SER_PDU_SIZE_MIN     4       /*!< Modbus RTU帧的最小尺寸 */
#define MB_SER_PDU_SIZE_MAX     256     /*!< Modbus RTU帧的最大尺寸 */
#define MB_SER_PDU_SIZE_CRC     2       /*!< PDU中CRC字段的大小 */
#define MB_SER_PDU_ADDR_OFF     0       /*!< Ser-PDU中从机地址的偏移量 */
#define MB_SER_PDU_PDU_OFF      1       /*!< 串行协议数据单元（Ser-PDU）中Modbus协议数据单元（Modbus-PDU）的偏移量 */


/* ----------------------- Static variables ---------------------------------*/
uint8_t  WHT_RTU_Buffer[MB_SER_PDU_SIZE_MAX];

/* ----------------------- Start implementation -----------------------------*/
eMBErrorCode WHT_MB_RTU_Init(uint8_t ucSlaveAddress)
{
    eMBErrorCode    eStatus = MB_ENOERR;

    /* Modbus RTU使用8个数据位*/
    if(WHT_MB_Port_Serial_Init() != true )
    {
        eStatus = MB_EPORTERR;
    }
    return eStatus;
}
eMBErrorCode WHT_MB_RTU_Receive( uint8_t * pucRcvAddress, uint8_t ** pucFrame, uint16_t * pusLength )
{
    uint16_t usRcvBufferPos;
    eMBErrorCode    eStatus = MB_ENOERR;

    usRcvBufferPos = WHT_FreeModBus_Scanf(WHT_RTU_Buffer, sizeof(WHT_RTU_Buffer));

    /* 长度和循环冗余校验检查 */
    if( (usRcvBufferPos >= MB_SER_PDU_SIZE_MIN ) && (WHT_MB_CRC16(WHT_RTU_Buffer, usRcvBufferPos) == 0))
    {
        /* 保存地址字段。所有帧都传递到上层，关于是否使用某一帧的决定在那里做出 */
        *pucRcvAddress = WHT_RTU_Buffer[MB_SER_PDU_ADDR_OFF];

        /* Modbus-PDU的总长度等于Modbus-串行线路-PDU减去地址字段和CRC校验和的大小 */
        *pusLength = ( uint16_t )( usRcvBufferPos - MB_SER_PDU_PDU_OFF - MB_SER_PDU_SIZE_CRC );

        /* 向调用者返回Modbus协议数据单元（PDU）的起始部分 */
        *pucFrame = ( uint8_t * ) & WHT_RTU_Buffer[MB_SER_PDU_PDU_OFF];
    }
    else
    {
        printf("MB RTU CRC ERROR!!!\r\n");
        printf("CRC=0x%02x\r\n", WHT_MB_CRC16(WHT_RTU_Buffer, usRcvBufferPos - MB_SER_PDU_SIZE_CRC));
        eStatus = MB_EIO;
    }
    return eStatus;
}
eMBErrorCode WHT_MB_RTU_Send( uint8_t ucSlaveAddress, const uint8_t * pucFrame, uint16_t usLength )
{
    volatile uint8_t *pucSndBufferCur;
    uint16_t usSndBufferCount;
    uint16_t          usCRC16;

    /* Modbus协议数据单元（Modbus-PDU）前的第一个字节是从站地址 */
    pucSndBufferCur = ( uint8_t * ) pucFrame - 1;
    usSndBufferCount = 1;

    /* 现在将Modbus协议数据单元（Modbus-PDU）复制到Modbus串行线路协议数据单元（Modbus-Serial-Line-PDU）中 */
    pucSndBufferCur[MB_SER_PDU_ADDR_OFF] = ucSlaveAddress;
    usSndBufferCount += usLength;

    /* 计算Modbus串行线路协议数据单元（Modbus-Serial-Line-PDU）的CRC16校验和 */
    usCRC16 = WHT_MB_CRC16( ( uint8_t * ) pucSndBufferCur, usSndBufferCount );
    WHT_RTU_Buffer[usSndBufferCount++] = ( uint8_t )( usCRC16 & 0xFF );
    WHT_RTU_Buffer[usSndBufferCount++] = ( uint8_t )( usCRC16 >> 8 );

    /* 启动发送传输 */
    WHT_FreeModBus_Printf((uint8_t*)pucSndBufferCur, usSndBufferCount);
    return MB_ENOERR;
}
